package com.example.sale.Controller;
import com.example.sale.Service.IProductDetailService;
import com.example.sale.True.ProductDetail;
import com.example.sale.True.User;
import com.example.sale.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("productDetail")
public class ProductDetailController {
    @Autowired
    private IProductDetailService iProductDetailService;
    @Autowired
    private JwtUtil jwtUtil;
    @PostMapping("/post")
    public Map<String,Object> postProduct(@RequestBody ProductDetail productDetail, HttpServletRequest request){
        String token = request.getHeader("token");
        User zhi = jwtUtil.parseToken(token, User.class);
        Integer userid = zhi.getId(); // 假设id是String类型
        productDetail.setUserid(userid);
        System.out.println(productDetail);
        Map<String,Object> result = new HashMap<>();
        System.out.println("6666");
        boolean ProductDetailExists = iProductDetailService.isProductDetailExists(productDetail.getName(),userid);
        System.out.println(ProductDetailExists);
        System.out.println("7777");
        System.out.println(productDetail.getNumber());
        if(productDetail.getNumber()==0){
            result.put("status","zero");
            return result;
        }
        if(productDetail.getNumber()<0){
            result.put("status","lessZero");
            return result;
        }
        if(ProductDetailExists==false){
            iProductDetailService.save(productDetail);
            result.put("status","success");
        }
        else{
            result.put("status","false");
        }
        return result;
    }
    @GetMapping("GetBYUserId")
    public Map<String,Object> postProduct(HttpServletRequest request){
        String token = request.getHeader("token");
        User zhi = jwtUtil.parseToken(token, User.class);
        Integer userid = zhi.getId(); // 假设id是String类型;
        System.out.println(userid);
        List<ProductDetail> productDetailList = iProductDetailService.GetBYUserid(userid);
        Map<String,Object> result = new HashMap<>();
        result.put("data",productDetailList);
        return result;
    }
    @PutMapping("/ChangeNumber")
    public Map<String, Object> changeData(@RequestBody ProductDetail productDetail){
        Map<String, Object> response = new HashMap<>();
        response.put("status", iProductDetailService.updateById(productDetail));
        return response;
    }
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteData(@PathVariable Integer id){
        Map<String,Object> result = new HashMap<>();
        result.put("id",iProductDetailService.removeById(id));
        return result;
    }
}
